import React, { Component, createRef } from "react";

import FilterTitle from "../FilterTitle";
import FilterMore from "../FilterMore";
import FilterPicker from "../FilterPicker";

// 导入自定义的axios
import { API } from "../../../../utils/api.js";
import styles from "./index.module.css";

import { Spring } from "react-spring/renderprops";
// 标题高亮状态
// true 表示高亮: false 表示不高亮
const titleSelectedStatus = {
  area: false,
  mode: false,
  price: false,
  more: false,
};

const selectedValues = {
  area: ["area", "null"],
  mode: ["null"],
  price: ["null"],
  more: [],
};

export default class Filter extends Component {
  mask = createRef();
  state = {
    titleSelectedStatus,
    // 控制 FilterPicker 或 FilterMore 组件的展示或隐藏
    openType: "",
    // 所有筛选条件数据
    filtersData: {},
    // 筛选条件的选中值
    selectedValues,
    opacity: 0,
  };
  componentDidMount() {
    // 获取body
    this.body = document.body;
    this.getFiltersData();
  }

  // 关闭后标题高亮逻辑
  onCancelTitle = (
    type,
    newTitleSelectedStatus = { ...this.state.titleSelectedStatus }
  ) => {
    const { selectedValues } = this.state;
    const selectedVal = selectedValues[type];

    if (
      type === "area" &&
      (selectedVal.length !== 2 || selectedVal[0] !== "area")
    ) {
      // 高亮
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal[0] !== undefined) {
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }

    return newTitleSelectedStatus;
  };
  // 封装获取所有筛选条件的方法
  async getFiltersData() {
    // 获取当前定位城市id
    const { value } = JSON.parse(localStorage.getItem("hkzf_city"));
    const res = await API.get(`/houses/condition?id=${value}`);

    this.setState({
      filtersData: res.data.body,
    });
  }
  // 点击标题菜单实现高亮
  onTitleClick = (type) => {
    // 给 body 添加样式
    this.body.className = "body-fixed";
    const { titleSelectedStatus } = this.state;

    // 创建新的标题选中状态对象
    let newTitleSelectedStatus = { ...titleSelectedStatus };

    // 遍历标题选中状态对象
    // Object.keys() 得到 ['area','mode','price','more']
    Object.keys(titleSelectedStatus).forEach((item) => {
      newTitleSelectedStatus = this.onCancelTitle(item, newTitleSelectedStatus);
    });
    newTitleSelectedStatus[type] = true;
    this.setState({
      titleSelectedStatus: newTitleSelectedStatus,
      // 展示对话框
      openType: type,
    });
  };

  // 取消 (隐藏对话框)
  onCancel = (type) => {
    this.body.className = "";
    //隐藏
    this.setState({
      openType: "",
      titleSelectedStatus: this.onCancelTitle(type),
    });
  };

  // 确定 (隐藏对话框)
  onSave = (type, value) => {
    this.body.className = "";

    const newSelectedValues = {
      ...this.state.selectedValues,
      // 只更新当前 type 对应的选中值
      [type]: value,
    };
    console.log("最新的值:", newSelectedValues);
    const { area, mode, price, more } = newSelectedValues;

    // 筛选条件数据
    const filters = {};

    // 区域
    const areaKey = area[0];
    let areaValue = "null";
    if (area.length === 3) {
      areaValue = area[2] !== "null" ? area[2] : area[1];
    }
    filters[areaKey] = areaValue;

    // 方式和租金
    filters.mode = mode[0];
    filters.price = price[0];

    // 更多筛选条件 more
    filters.more = more.join(",");

    // 调用父组件中的方法,将筛选数据传递给父组件
    this.props.onFilter(filters);

    // 隐藏对话框
    this.setState(
      {
        openType: "",
        selectedValues: newSelectedValues,
      },
      () => {
        this.setState({
          titleSelectedStatus: this.onCancelTitle(type),
        });
      }
    );
  };

  // 渲染 FilterPicker 组件的方法
  renderFilterPicker() {
    const {
      openType,
      filtersData: { area, subway, rentType, price },
      selectedValues,
    } = this.state;
    if (openType !== "area" && openType !== "mode" && openType !== "price") {
      return null;
    }

    // 根据 openType 来拿到当前筛选条件数据
    let data = [];
    let cols = 0;
    let defaultValue = selectedValues[openType];
    switch (openType) {
      case "area":
        // 获取到区域数据
        data = [area, subway];
        cols = 3;
        break;
      case "mode":
        data = rentType;
        cols = 1;
        break;
      case "price":
        data = price;
        cols = 1;

        break;
      default:
        break;
    }
    return (
      <FilterPicker
        onCancel={this.onCancel}
        onSave={this.onSave}
        data={data}
        cols={cols}
        key={openType}
        type={openType}
        defaultValue={defaultValue}
      />
    );
  }

  // 渲染 FilterMore 组件的方法
  renderFilterMore() {
    const {
      openType,
      filtersData: { roomType, oriented, floor, characteristic },
      selectedValues,
    } = this.state;
    const defaultValue = selectedValues[openType];
    if (openType !== "more") {
      return null;
    }
    return (
      <FilterMore
        data={{ roomType, oriented, floor, characteristic }}
        type={openType}
        onSave={this.onSave}
        onCancel={this.onCancel}
        defaultValue={defaultValue}
      />
    );
  }

  // 渲染遮罩层 div
  renderMask() {
    const { openType } = this.state;
    const isHide = openType === "more" || openType === "";
    return (
      <Spring from={{ opacity: 0 }} to={{ opacity: isHide ? 0 : 1 }}>
        {(props) => {
          if (props.opacity === 0) {
            return null;
          }
          return (
            <div
              style={props}
              className={styles.mask}
              onClick={() => this.onCancel(openType)}
            />
          );
        }}
      </Spring>
    );
  }

  render() {
    const { titleSelectedStatus } = this.state;
    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}
        {this.renderMask()}

        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle
            titleSelectedStatus={titleSelectedStatus}
            onClick={this.onTitleClick}
          />

          {/* 前三个菜单对应的内容 */}
          {this.renderFilterPicker()}

          {/* 最后一个菜单对应的内容 */}
          {this.renderFilterMore()}
        </div>
      </div>
    );
  }
}
